﻿using LBSoft.Business;
using LBSoft.Common.DotNetBean;
using LBSoft.Common.DotNetCode;
using LBSoft.Common.DotNetConfig;
using LBSoft.Common.DotNetExt;
using LBSoft.Common.DotNetJson;
using LBSoft.Common.DotNetUI;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace LBSoft.HplusAdmin
{
    /// <summary>
    /// LoginHandle 的摘要说明
    /// </summary>
    public class LoginHandle : IHttpHandler, IRequiresSessionState
    {
        HttpContext con;
        mJsonResult json = new mJsonResult();
        Common_Dal systemidao = new Common_Dal();

        public void ProcessRequest(HttpContext context)
        {
            con = context;
            switch (con.Request["PostType"])
            {
                case "login": Login(); break;   //登录
                case "loginOut": LoginOut(); break;   //退出登录
            }
        }

        #region 登录
        private void Login()
        {
            string userAccount = con.Request["UserAccount"].ToString2();
            string userPwd = con.Request["UserPwd"].ToString2();
            string validCode = con.Request["ValidCode"].ToString2();
            if ((con.Session["VerifyCode"].ToString2().ToLower()) != (validCode.ToString2().Trim().ToLower()))
            {
                json.success = false;
                json.msg = "验证码错误！";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }
            DataTable dt = systemidao.GetDataTableBySQL(new StringBuilder(string.Format(@"select * from Sys_UserInfo where UserAccount='{0}' ", userAccount)));
            if (dt == null || dt.Rows.Count == 0)
            {
                json.success = false;
                json.msg = "当前用户不存在！";
                con.Response.Write(JsonConvert.SerializeObject(json));
                return;
            }

            UserInfo_Dal userInfo_Dal = new UserInfo_Dal();
            DataTable dtlogin = userInfo_Dal.UserLogin(userAccount.Trim(), userPwd.Trim());
            if (dtlogin != null && dtlogin.Rows.Count > 0)
            {
                int isLock = dt.Rows[0]["IsLock"].ToInt32(0);
                if (isLock == 1)
                {
                    json.success = false;
                    json.msg = "当前用户已锁定，暂停使用！";
                    con.Response.Write(JsonConvert.SerializeObject(json));
                    return;
                }

                IPScanerHelper objScan = new IPScanerHelper();
                string basePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
                objScan.DataPath = Path.GetFullPath(basePath + ConfigHelper.GetAppSettings("QQWryPath"));
                string ip = RequestHelper.GetIP();
                objScan.IP = ip;
                string loginAddress = objScan.IPLocation();

                userInfo_Dal.SysLoginLog(userAccount, loginAddress, "登录成功", "WEB");

                //生成验证信息
                FormsAuthentication.SetAuthCookie(userAccount, false);

                //设置太长导致cookie限制 以至于系统登陆不了
                RequestSession.AddSessionUser(new SessionUser
                {
                    UserId = dtlogin.Rows[0]["GUID"].ToString2(),
                    UserAccount = dtlogin.Rows[0]["UserAccount"].ToString2(),
                    UserName = dtlogin.Rows[0]["UserName"].ToString2(),
                    UserType = dtlogin.Rows[0]["UserType"].ToInt32()
                });

                json.success = true;
                json.msg = "登录成功！";
            }
            else
            {
                json.success = false;
                json.msg = "登录信息有误！";
            }
            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        #region 退出登录
        private void LoginOut()
        {
            FormsAuthentication.SignOut();
            json.success = true;
            json.msg = "退出成功！";
            con.Response.Write(JsonConvert.SerializeObject(json));
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}